<template>
  <el-tooltip
    class="item"
    effect="dark"
    content="回到顶部"
    placement="left-start"
  >
    <transition name="fade-scale">
      <div
        id="scrolltop"
        :style="scrolltopstyle"
        v-if="scrolltopif"
        v-show="scrolltopShow"
        @click="scrolltop()"
      >
        <slot name="scrolltopImg"
          ><img src="@/assets/img/icon/top.svg"
        /></slot>
        <div id="scrolltopText"><slot name="scrolltopText"></slot></div>
      </div>
    </transition>
  </el-tooltip>
</template>

<script>
import Bus from "@/assets/js/bus.js";

export default {
  name: "ScrollTop",
  props: {
    width: {
      type: Number,
      default: 40,
    },
    height: {
      type: Number,
      default: 40,
    },
    backcolor: {
      type: String,
      default: "#f7f9fa",
    },
    color: {
      type: String,
      default: "#000000",
    },
  },
  data() {
    return {
      scrolltopif: true,
      scrolltopShow: false,
      scrolltopNumber: "",
      timer: null,
    };
  },
  mounted() {
    Bus.$on("isscroll", (data) => {
      this.scrolltopNumber = data.scrolltop;
    });
  },
  beforeDestroy(){
    this.timer=null;
  },
  methods: {
    scrolltop() {
        this.timer = setInterval(() => {
        let speed = Math.floor(-this.scrolltopNumber / 4);
        window.pageYOffset =
          document.documentElement.scrollTop =
          document.body.scrollTop =
            this.scrolltopNumber + speed;
        if (this.scrolltopNumber <= 0) {
          clearInterval(this.timer);
        }
      }, 20);
    },
  },
  computed: {
    scrolltopstyle() {
      return {
        height: this.height + "px",
        width: this.width + "px",
        backgroundColor: this.backcolor,
        color: this.color,
      };
      /* js里不能使用-连接,例如background-color,要用驼峰代替,写成backgroundColor */
    },
  },
  watch: {
    scrolltopNumber: function () {
      if (this.scrolltopNumber != 0) {
        this.scrolltopShow = true;
      } else {
        this.scrolltopShow = false;
      }
    },
  },
};
</script>

<style scoped>
#scrolltop {
  border-radius: 5px;
  box-shadow: 1px 1px 3px gray;
  cursor: pointer;
  display: flex;
  justify-content: center;
  align-items: center;
  overflow: hidden;
  margin-bottom: 10px;
  border: 1px solid #e5e9ef;
}
#scrolltop img {
  width: 50px;
  height: 30px;
}
#scrolltopText {
  font-weight: bolder;
  font-size: 14px;
}
#scrolltop:hover {
  opacity: 0.5;
}
</style>
